from flask import Flask,render_template,request,url_for,send_from_directory
import os
from PIL import Image #pip install pillow
app = Flask(__name__)

#允许上传的后缀名
ALLOWED_EXTENSIONS = set(['png','jpg','jpeg','gif'])
#配置上传的位置
app.config['UPLOAD_FOLDER'] = os.getcwd()
#限定文件上传的大小
app.config['MAX_CONTENT_LENGTH'] = 1024*1024*8


#写一个方法 获取后缀名 然后查看是否在允许的列表中
def allow_file(filename):
    return "." in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS

#生成随机的字符串
def random_string(length=20):
    import random
    base_str = 'qwertyuiopasdfghjklzxcvbnm0123456789'
    return ''.join(random.choice(base_str) for i in range(length))


#构造文件的url地址 也就是说  http://127.0.0.1:5058/upload/guanxi.jpg
@app.route('/upload/<filename>')
def uploaded(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],filename)




@app.route('/')
def index():
    return random_string()

@app.route('/upload/',methods=['GET','POST'])
def upload():
    img_url = None
    if request.method == 'POST':
        file = request.files.get('photo')
        if file and allow_file(file.filename):
            # print(file.filename.rsplit('.',1)[0])
            suffix = os.path.splitext(file.filename)[-1]
            filename = random_string()+suffix
            pathname = os.path.join(app.config['UPLOAD_FOLDER'],filename)
            file.save(pathname)
            # cat /etc/passwd  | grep 'root'
            #处理图片 分为三步
            # 1.打开图片
            img  = Image.open(pathname)
            #2.重设尺寸
            img.thumbnail((128,128))
            #3.保存
            img.save(pathname)
            img_url = url_for('uploaded',filename=filename)
    return render_template('index.html',img_url=img_url)

if __name__ == '__main__':
    app.run()
